/**
 * This software was produced for the U. S. Government
 * under Contract No. FA8721-09-C-0002, and is
 * subject to the Rights in Noncommercial Computer Software
 * and Noncommercial Computer Software Documentation Clause
 * (DFARS) 252.227-7014 (JUN 1995)
 * 
 * (c) 2009 The MITRE Corporation. All Rights Reserved.
 *
 * SPMIF to OPNET Translator
 * Author: EWALTERS
 * Created: 4:14:36 PM, Apr 21, 2008
 * MITRE Corporation
 */
package com.mitre.spmif2opnet.generation;

import java.util.Hashtable;
import java.util.List;
import java.util.Map;

import com.mitre.spmif2opnet.generation.ir.Link;

/**
 * This class allocates  transmit and receive ports according to the number
 *  of connections per device
 */
public class LinkAllocator {
	
	/**
	 *  Map device names to their eligible "from" ports
	 */
	private Map<String, Integer> _from_ports;
	/**
	 *  Map device names to their eligible "to" ports
	 */
	private Map<String, Integer> _to_ports;
	
	/**
	 * Default constructor
	 */
	public LinkAllocator() {
		_from_ports = new Hashtable<String, Integer>();
		_to_ports = new Hashtable<String, Integer>();
	}
	/**
	 * Allocate port numbers to the links
	 * @param links
	 */
	public void AllocateLinks(List<Link> links) {
		for (Link l : links) {
			String from_node = l.getFromNode(), to_node = l.getToNode();
			int from_port = 0, to_port = 0, from_rev_port = 0, to_rev_port = 0;

			if(_from_ports.containsKey(from_node)) {
				from_port = _from_ports.get(from_node).intValue();				
			}
			_from_ports.put(from_node, from_port + 1);
			
			if (_to_ports.containsKey(from_node)) {
				from_rev_port = _to_ports.get(from_node).intValue();
			}
			_to_ports.put(from_node, from_rev_port + 1);
			
			if(_to_ports.containsKey(to_node)) {
				to_port = _to_ports.get(to_node).intValue();				
			}
			_to_ports.put(to_node, to_port + 1);
			
			if(_from_ports.containsKey(to_node)) {
				to_rev_port = _from_ports.get(to_node).intValue();				
			}
			_from_ports.put(to_node, to_rev_port + 1);
			
			l.setFromTxPort(from_port);
			l.setFromRxPort(from_port);
			l.setToRxPort(to_port);
			l.setToTxPort(to_port);
		}
	}
}
